import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { WebsiteService } from '../services/WebsiteService';
import { CreateWebsiteRequest, UpdateWebsiteRequest } from '../types/group';

// 请求参数类型定义
interface WebsiteIdParams {
  id: string;
}

interface GroupIdParams {
  groupId: string;
}

interface SearchQuery {
  q: string;
}

interface ReorderWebsitesBody {
  websiteOrders: { id: string; order: number }[];
}

interface MoveWebsitesBody {
  websiteIds: string[];
  newGroupId: string;
}

export async function websiteRoutes(fastify: FastifyInstance) {
  // 获取所有网站
  fastify.get('/', {
    schema: {
      description: '获取所有网站列表',
      tags: ['网站管理'],
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'array',
              items: {
                type: 'object',
                properties: {
                  id: { type: 'string' },
                  name: { type: 'string' },
                  description: { type: 'string' },
                  url: { type: 'string' },
                  logo: { type: 'string' },
                  groupId: { type: 'string' },
                  order: { type: 'number' },
                  isActive: { type: 'boolean' },
                  createdAt: { type: 'string' },
                  updatedAt: { type: 'string' }
                }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest, reply: FastifyReply) => {
    const result = await WebsiteService.getAllWebsites();
    return reply.code(result.success ? 200 : 400).send(result);
  });

  // 根据分组ID获取网站列表
  fastify.get('/group/:groupId', {
    schema: {
      description: '根据分组ID获取网站列表',
      tags: ['网站管理'],
      params: {
        type: 'object',
        properties: {
          groupId: { type: 'string', description: '分组ID' }
        },
        required: ['groupId']
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'array',
              items: {
                type: 'object',
                properties: {
                  id: { type: 'string' },
                  name: { type: 'string' },
                  description: { type: 'string' },
                  url: { type: 'string' },
                  logo: { type: 'string' },
                  groupId: { type: 'string' },
                  order: { type: 'number' },
                  isActive: { type: 'boolean' },
                  createdAt: { type: 'string' },
                  updatedAt: { type: 'string' }
                }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Params: GroupIdParams }>, reply: FastifyReply) => {
    const { groupId } = request.params;
    const result = await WebsiteService.getWebsitesByGroupId(groupId);
    return reply.code(result.success ? 200 : 404).send(result);
  });

  // 获取网站详情
  fastify.get('/:id', {
    schema: {
      description: '获取网站详情',
      tags: ['网站管理'],
      params: {
        type: 'object',
        properties: {
          id: { type: 'string', description: '网站ID' }
        },
        required: ['id']
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                id: { type: 'string' },
                name: { type: 'string' },
                description: { type: 'string' },
                url: { type: 'string' },
                logo: { type: 'string' },
                groupId: { type: 'string' },
                order: { type: 'number' },
                isActive: { type: 'boolean' },
                createdAt: { type: 'string' },
                updatedAt: { type: 'string' }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Params: WebsiteIdParams }>, reply: FastifyReply) => {
    const { id } = request.params;
    const result = await WebsiteService.getWebsiteById(id);
    return reply.code(result.success ? 200 : 404).send(result);
  });

  // 创建网站
  fastify.post('/', {
    schema: {
      description: '创建新网站',
      tags: ['网站管理'],
      body: {
        type: 'object',
        properties: {
          name: { type: 'string', description: '网站名称' },
          description: { type: 'string', description: '网站描述' },
          url: { type: 'string', description: '网站URL' },
          logo: { type: 'string', description: '网站Logo URL' },
          groupId: { type: 'string', description: '所属分组ID' },
          order: { type: 'number', description: '排序顺序' },
          isActive: { type: 'boolean', description: '是否启用' }
        },
        required: ['name', 'url', 'groupId']
      },
      response: {
        201: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                id: { type: 'string' },
                name: { type: 'string' },
                description: { type: 'string' },
                url: { type: 'string' },
                logo: { type: 'string' },
                groupId: { type: 'string' },
                order: { type: 'number' },
                isActive: { type: 'boolean' },
                createdAt: { type: 'string' },
                updatedAt: { type: 'string' }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Body: CreateWebsiteRequest }>, reply: FastifyReply) => {
    const result = await WebsiteService.createWebsite(request.body);
    return reply.code(result.success ? 201 : 400).send(result);
  });

  // 更新网站
  fastify.put('/:id', {
    schema: {
      description: '更新网站信息',
      tags: ['网站管理'],
      params: {
        type: 'object',
        properties: {
          id: { type: 'string', description: '网站ID' }
        },
        required: ['id']
      },
      body: {
        type: 'object',
        properties: {
          name: { type: 'string', description: '网站名称' },
          description: { type: 'string', description: '网站描述' },
          url: { type: 'string', description: '网站URL' },
          logo: { type: 'string', description: '网站Logo URL' },
          groupId: { type: 'string', description: '所属分组ID' },
          order: { type: 'number', description: '排序顺序' },
          isActive: { type: 'boolean', description: '是否启用' }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                id: { type: 'string' },
                name: { type: 'string' },
                description: { type: 'string' },
                url: { type: 'string' },
                logo: { type: 'string' },
                groupId: { type: 'string' },
                order: { type: 'number' },
                isActive: { type: 'boolean' },
                createdAt: { type: 'string' },
                updatedAt: { type: 'string' }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Params: WebsiteIdParams; Body: UpdateWebsiteRequest }>, reply: FastifyReply) => {
    const { id } = request.params;
    const result = await WebsiteService.updateWebsite(id, request.body);
    return reply.code(result.success ? 200 : 400).send(result);
  });

  // 删除网站
  fastify.delete('/:id', {
    schema: {
      description: '删除网站',
      tags: ['网站管理'],
      params: {
        type: 'object',
        properties: {
          id: { type: 'string', description: '网站ID' }
        },
        required: ['id']
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Params: WebsiteIdParams }>, reply: FastifyReply) => {
    const { id } = request.params;
    const result = await WebsiteService.deleteWebsite(id);
    return reply.code(result.success ? 200 : 400).send(result);
  });

  // 搜索网站
  fastify.get('/search', {
    schema: {
      description: '搜索网站',
      tags: ['网站管理'],
      querystring: {
        type: 'object',
        properties: {
          q: { type: 'string', description: '搜索关键词' }
        },
        required: ['q']
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'array',
              items: {
                type: 'object',
                properties: {
                  id: { type: 'string' },
                  name: { type: 'string' },
                  description: { type: 'string' },
                  url: { type: 'string' },
                  logo: { type: 'string' },
                  groupId: { type: 'string' },
                  order: { type: 'number' },
                  isActive: { type: 'boolean' },
                  createdAt: { type: 'string' },
                  updatedAt: { type: 'string' }
                }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Querystring: SearchQuery }>, reply: FastifyReply) => {
    const { q } = request.query;
    const result = await WebsiteService.searchWebsites(q);
    return reply.code(result.success ? 200 : 400).send(result);
  });

  // 切换网站激活状态
  fastify.patch('/:id/toggle', {
    schema: {
      description: '切换网站启用/禁用状态',
      tags: ['网站管理'],
      params: {
        type: 'object',
        properties: {
          id: { type: 'string', description: '网站ID' }
        },
        required: ['id']
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                id: { type: 'string' },
                name: { type: 'string' },
                description: { type: 'string' },
                url: { type: 'string' },
                logo: { type: 'string' },
                groupId: { type: 'string' },
                order: { type: 'number' },
                isActive: { type: 'boolean' },
                createdAt: { type: 'string' },
                updatedAt: { type: 'string' }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Params: WebsiteIdParams }>, reply: FastifyReply) => {
    const { id } = request.params;
    const result = await WebsiteService.toggleWebsiteStatus(id);
    return reply.code(result.success ? 200 : 404).send(result);
  });

  // 重新排序网站
  fastify.put('/reorder', {
    schema: {
      description: '重新排序网站',
      tags: ['网站管理'],
      body: {
        type: 'object',
        properties: {
          websiteOrders: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                id: { type: 'string', description: '网站ID' },
                order: { type: 'number', description: '新的排序顺序' }
              },
              required: ['id', 'order']
            }
          }
        },
        required: ['websiteOrders']
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Body: ReorderWebsitesBody }>, reply: FastifyReply) => {
    const { websiteOrders } = request.body;
    const result = await WebsiteService.reorderWebsites(websiteOrders);
    return reply.code(result.success ? 200 : 400).send(result);
  });

  // 批量移动网站到新分组
  fastify.put('/move', {
    schema: {
      description: '批量移动网站到新分组',
      tags: ['网站管理'],
      body: {
        type: 'object',
        properties: {
          websiteIds: {
            type: 'array',
            items: { type: 'string' },
            description: '要移动的网站ID列表'
          },
          newGroupId: { type: 'string', description: '目标分组ID' }
        },
        required: ['websiteIds', 'newGroupId']
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                movedCount: { type: 'number' }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest<{ Body: MoveWebsitesBody }>, reply: FastifyReply) => {
    const { websiteIds, newGroupId } = request.body;
    const result = await WebsiteService.moveWebsitesToGroup(websiteIds, newGroupId);
    return reply.code(result.success ? 200 : 400).send(result);
  });

  // 获取网站统计信息
  fastify.get('/stats', {
    schema: {
      description: '获取网站统计信息',
      tags: ['网站管理'],
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
            data: {
              type: 'object',
              properties: {
                total: { type: 'number', description: '总网站数' },
                active: { type: 'number', description: '启用的网站数' },
                inactive: { type: 'number', description: '禁用的网站数' },
                byGroup: {
                  type: 'array',
                  items: {
                    type: 'object',
                    properties: {
                      groupId: { type: 'string' },
                      groupName: { type: 'string' },
                      count: { type: 'number' }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }, async (request: FastifyRequest, reply: FastifyReply) => {
    const result = await WebsiteService.getWebsiteStats();
    return reply.code(result.success ? 200 : 400).send(result);
  });
}